# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4

##
## Copyright (C) 2009 - George Y. Kussumoto <georgeyk.dev@gmail.com>
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., or visit: http://www.gnu.org/.
##
##

import random

import google.appengine.ext.db as db

from twitheroapp.models.hero import Hero


class Battle(db.Model):
    """Battle object implementation.
    #TODO: improve docstrings
    """
    (FIGHTER_WON,
     OPPONENT_WON,
     DRAW) = range(3)

    date = db.DateTimeProperty(auto_now_add=True)
    fighter = db.ReferenceProperty(Hero, required=True,
                                   collection_name='fighter_set')
    opponent = db.ReferenceProperty(Hero, required=True,
                                    collection_name='opponent_set')
    result = db.IntegerProperty(default=None)

    #
    # Public API
    #

    def set_fighter_victory(self):
        self.result = Battle.FIGHTER_WON


    def set_opponent_victory(self):
        self.result = Battle.OPPONENT_WON


    def set_draw_battle(self):
        self.result = Battle.DRAW


    @property
    def attribute(self):
        self._choosen_attr = random.choice(Hero.get_attributes())
        return self._choosen_attr

    @property
    def show_winner(self):
        if self.result == Battle.FIGHTER_WON:
             return self.fighter.name
        elif self.result == Battle.OPPONENT_WON:

            return self.opponent.name
        else:

            return u'DRAW!'

    #
    # Private API
    #

    def do_fight(self):
        if self.attribute:
            pass

        fighter = getattr(self.fighter, self._choosen_attr)
        opponent = getattr(self.opponent, self._choosen_attr)

        if fighter > opponent:
         self.set_fighter_victory()
        elif opponent > fighter:
         self.set_opponent_victory()
        else:
         self.set_draw_battle()
         self.opponent.update()

        self.fighter.update()
        self.fighter.put()
        self.opponent.update()
        self.opponent.put()
